<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="产品编辑"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 60px);" :show-scrollbar="false">
			<view style=" background-color:#EFEDE9;">
				<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">服务信息</view>
			</view>
			<u-form :model="form" ref="uForm">
				<u-form-item :required="true" label-width="230" label="产品/服务名称" prop="productServeName"
					style="padding-left: 10px; padding-right: 10px;">
					<u-input v-model="form.productServeName" />
				</u-form-item>

				<u-form-item :required="true" label-width="230" label="服务商名称" prop="serviceName"
					style="padding-left: 10px; padding-right: 10px;">
					<u-input v-model="form.serviceName" />
				</u-form-item>
				<u-form-item :required="true" label-width="230" label="服务介绍" prop="serviceIntroduction"
					style="padding-left: 10px; padding-right: 10px;">
					<u-input type="textarea" height="100" v-model="form.serviceIntroduction" />
				</u-form-item>
				<view class="text-right text-BEBFE8 pr-2">({{ wordCount }} / {{maxCharacters }})</view>
				<u-form-item :required="true" label-width="230" label="服务介绍详情"
					style="padding-left: 10px; padding-right: 10px;">
					<u-upload ref="uUpload" :file-list="fileList" :max-size="4 * 1024 * 1024"
						:form-data="{'biz':'temp'}" :header="header" @on-success="uploadSuccess"
						:action="getUploadUrl()" max-count="5">
					</u-upload>
				</u-form-item>
				<view class="font-12 text-FF0000 pl-1 pb-2">图片大小限制不能超过4MB,最多能上传五张图片</view>
				<u-form-item :required="true" label-width="230" label="服务价格(元)" prop="servicePrice"
					style="padding-left: 10px; padding-right: 10px;">
					<u-input v-model="form.servicePrice" placeholder="￥" />
				</u-form-item>
				<!-- 	<u-form-item :required="true" label-width="230"  label="服务流程" style="padding-left: 10px; padding-right: 10px;">
					<u-input type="textarea" height="50" v-model="form.serviceFlow"  />
				</u-form-item>
				<u-form-item :required="true" label-width="230"  label="售后服务" style="padding-left: 10px; padding-right: 10px;">
					<u-input type="textarea" height="50"  v-model="form.serviceInform"  />
				</u-form-item> -->
				<view style=" background-color:#EFEDE9;">
					<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">上/下架状态</view>
				</view>
				<u-form-item :required="true" label-width="230" style="padding-left: 10px; padding-right: 10px;"
					label="上/下架状态">
					<u-input v-model="form.productStatusText" type="select" :border="false" @click="showList = true" />
					<u-action-sheet :list="actionSheetList" v-model="showList"
						@click="actionSheetCallback"></u-action-sheet>
				</u-form-item>
			</u-form>
			<ferrButton title="保存修改" @click="saveEdit()"></ferrButton>
		</scroll-view>
	</view>
</template>

<script>
	import $H from "@/common/free-lib/request.js";
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import calendar from "@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue"
	export default {
		components: {
			ferrButton,
			calendar
		},

		data() {
			return {
				rules: {
					productServeName: [{
							required: true,
							message: '产品/服务名称不能为空',
							trigger: ['change', 'blur'],
						}

					],
					serviceName: [{
						required: true,
						message: '服务商名称不能为空',
						trigger: ['change', 'blur'],
					}],
				servicePrice: [
				          
				          {
				            validator: (rule, value, callback) => {
				              const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
				              if (value === undefined || value === null || value === '') {
				                callback(new Error('价格不能为空'));
				              } else if (!reg.test(value)) {
				                callback(new Error('请输入非负数字，可以有最多两位小数'));
				              } else {
				                callback();
				              }
				            },
				            trigger: ['change', 'blur']
				          }
				        ],
					// serviceIntroduction: [{
					// 	required: true,
					// 	message: '服务介绍不能为空',
					// 	trigger: ['change', 'blur'],
					// }],
					// servicePrice: [{
					// 		required: true,
					// 		message: '服务价格不能为空',
					// 		trigger: ['change', 'blur'],
					// 	},
					// 	{
					// 		required: true,

					// 		type: 'number',
					// 		message: '请输入数字',
					// 	}
					// ],

				},
				form: {
					id: '',
					productServeName: "",
					serviceName: '',
					serviceIntroduction: '',
					servicePrice: '',
					serviceFlow: '',
					serviceInform: '',
					productStatus: '',
					productStatusText: '',
					updateTime: '',
					upperUserId: '',
					serviceIntroductionUrl: ''
				},
				value: '',
				showList: false,
				border: true,
				labelStyle: {
					paddingLeft: '13px',
				},
				actionSheetList: [{
						text: '上架',
						status: 1
					},
					{
						text: '下架',
						status: 0
					}
				],
				header: $H.getTokenHeader(),
				maxCharacters: 200,
			}
		},
		onLoad(options) {
			this.getProductInfo(options.id);
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		computed: {
			fileList() {
				return Array.isArray(this.form.serviceIntroductionUrl) ? this.form.serviceIntroductionUrl : [];
			},
			wordCount() {
				// 安全性检查，避免访问未定义的属性
				if (this.form.serviceIntroduction && typeof this.form.serviceIntroduction === 'string') {
					return this.form.serviceIntroduction.length;
				} else {
					return 0;
				}
			}	

		},
		methods: {

			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},
			uploadSuccess(response, file, ) {
				this.file = file;
			},

			getFullImageUrl(imagePath) {
				return getImageUrl(imagePath);
			},
			actionSheetCallback(index) {
				this.form.productStatus = this.actionSheetList[index].status;
				this.form.productStatusText = this.actionSheetList[index].text;
			},
			getProductInfo(id) {
				uni.showLoading({
					title: '加载中'
				});

				$H.get(
					"/upper/upperMarketProduct/queryById", {
						id,
					}, {}
				).then((res) => {
					if (!res.result) {
						uni.showToast({
							title: "未查询到相关信息",
							icon: "none",
						});
						return;
					}
					this.form.id = res.result.id;
					this.form.productServeName = res.result.productServeName;
					this.form.serviceName = res.result.serviceName;
					this.form.serviceIntroduction = res.result.serviceIntroduction;
					this.form.servicePrice = res.result.servicePrice;
					this.form.serviceFlow = res.result.serviceFlow;
					this.form.serviceInform = res.result.serviceInform;
					this.form.productStatus = res.result.productStatus;
					this.form.productStatusText = res.result.productStatus == 1 ? '上架' : '下架';
					this.form.upperUserId = res.result.upperUserId;
					if (res.result.serviceIntroductionUrl) {
						this.form.serviceIntroductionUrl = res.result.serviceIntroductionUrl.split(',').map(url =>
							({
								url: this.getFullImageUrl(url)
							}));
					} else {
						this.form.serviceIntroductionUrl = [];
					}
					uni.hideLoading();
				}).catch(error => {
					console.error('请求出错', error); // 处理任何错误
					uni.showToast({
						title: "查询错误",
						icon: "none",
					});
					uni.hideLoading();
				})

			},
		saveEdit() {
		    let files = this.$refs.uUpload.lists.filter(val => {
		        return val.progress == 100;
		    });
		
		    // Check if no files are uploaded
		    if (files.length === 0 && (!this.form.serviceIntroductionUrl || this.form.serviceIntroductionUrl.length === 0)) {
		        this.form.serviceIntroductionUrl = ""; // Set default image URL or empty string
		        uni.showToast({
		            title: '请上传文件',
		            icon: 'none'
		        });
		        return;
		    }
		
		    this.$refs.uForm.validate(valid => {
		        if (valid) {
		            uni.showLoading({
		                title: '加载中'
		            });
		
		            // Get the uploaded file URLs
		            const uploadedFileUrls = files
		                .filter(file => file.response?.message)
		                .map(file => file.response.message);
		
		            // Concatenate default image URLs with uploaded file URLs
		            let allFileUrls = [];
		            if (Array.isArray(this.form.serviceIntroductionUrl)) {
		                allFileUrls = this.form.serviceIntroductionUrl.map(defaultImage => defaultImage.url);
		            }
		            allFileUrls = allFileUrls.concat(uploadedFileUrls).join(',');
		
		            $H.post(
		                "/upper/upperMarketProduct/upper/edit", {
		                    id: this.form.id,
		                    productServeName: this.form.productServeName,
		                    serviceName: this.form.serviceName,
		                    serviceIntroduction: this.form.serviceIntroduction,
		                    servicePrice: this.form.servicePrice,
		                    serviceFlow: this.form.serviceFlow,
		                    serviceInform: this.form.serviceInform,
		                    productStatus: this.form.productStatus,
		                    upperUserId: this.form.upperUserId,
		                    serviceIntroductionUrl: allFileUrls
		                }, {}
		            ).then((res) => {
		                if (res.success) {
		                    uni.showToast({
		                        title: "修改成功",
		                        icon: "none",
		                        duration: 4000
		                    });
		                    setTimeout(() => {
		                        uni.navigateBack({
		                            delta: 1
		                        });
		                    }, 4000);
		                } else {
		                    uni.showToast({
		                        title: "修改失败",
		                        icon: "none",
		                    });
		                }
		                uni.hideLoading();
		            }).catch(error => {
		                console.error('请求出错', error);
		                uni.showToast({
		                    title: "修改错误",
		                    icon: "none",
		                });
		                uni.hideLoading();
		            })
		        } else {
		            return;
		        }
		    });
		},


		}
	}
</script>

<style>

</style>